import { useState } from 'react';
import { Form, Input, Button, Card, message, Spin, Checkbox, Row, Col } from 'antd';
import { UserOutlined, LockOutlined, LoginOutlined } from '@ant-design/icons';
import { history, useModel } from '@umijs/max';

import './styles.less'; // 引入样式文件
import { getCurrentUser, userLogin } from '@/services/userApi';

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const { initialState, setInitialState } = useModel('@@initialState');

  const onFinish = async (values: { username: string; password: string; remember: boolean }) => {
    setLoading(true);
    try {
      const response = await userLogin({
        username: values.username,
        password: values.password
      });
      
      if (response.access) {
        localStorage.setItem('token', response.access);
        localStorage.setItem('refreshToken', response.refresh);
        localStorage.setItem('user', JSON.stringify(response.user) || '{}');

        // 获取用户信息
        const userInfoResponse = await getCurrentUser();
        if (userInfoResponse) {
          setInitialState({
            ...initialState,
            currentUser: userInfoResponse,
          });
          
          message.success('登录成功');
          
          // 根据角色跳转到不同页面
          switch (userInfoResponse.role) {
            case 'admin':
              history.push('/dashboard');
              break;
            case 'librarian':
              history.push('/books/list');
              break;
            default:
              history.push('/books/list');
          }
        }
      }
    } catch (error: any) {
      message.error(error.response?.data?.detail || '登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-page">
      <div className="login-container">
        <div className="login-header">
          <div className="logo">
            <span className="logo-icon">📚</span>
            <h1>图书管理系统</h1>
          </div>
          <p className="slogan">知识改变命运，阅读丰富人生</p>
        </div>
        
        <Card className="login-card" bordered={false}>
          <Form
            form={form}
            name="login"
            onFinish={onFinish}
            size="large"
            initialValues={{ remember: true }}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input 
                prefix={<UserOutlined />} 
                placeholder="用户名" 
                autoComplete="username"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password 
                prefix={<LockOutlined />} 
                placeholder="密码" 
                autoComplete="current-password"
              />
            </Form.Item>

            <Form.Item name="remember" valuePropName="checked">
              <Checkbox>记住我</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                block
                loading={loading}
                icon={<LoginOutlined />}
              >
                {loading ? '登录中...' : '登录'}
              </Button>
            </Form.Item>
          </Form>
          
          <div className="login-footer">
            <Row justify="space-between">
              <Col>
                <a href="#">忘记密码?</a>
              </Col>
              <Col>
                <a href="#">注册账户</a>
              </Col>
            </Row>
          </div>
        </Card>
        
        <div className="login-info">
          <Row justify="center" gutter={24}>
            <Col>
              <div className="info-item">
                <div className="info-icon">🔒</div>
                <div className="info-text">安全可靠</div>
              </div>
            </Col>
            <Col>
              <div className="info-item">
                <div className="info-icon">⚡</div>
                <div className="info-text">快速便捷</div>
              </div>
            </Col>
            <Col>
              <div className="info-item">
                <div className="info-icon">📱</div>
                <div className="info-text">移动适配</div>
              </div>
            </Col>
          </Row>
        </div>
      </div>
    </div>
  );
};

export default Login;